<?php
require 'wsSocial/core/libs/facebook.php';
$userId = '100003607836279';
$appId = '257736501000629';
$secret = '0d61af484912e12a9f8796f1766b482c';
$count = 3;
$format = 'xml';
$user = "totoletest";

$facebook = getFacebookFeed($userId, $appId, $secret, $count, $format);
$twitter = getTwitterFeed($user, $count);

$messages = array_merge($facebook, $twitter);
uasort($messages, 'compare');
/*echo "<pre>";
print_r(array_values($messages));
echo "</pre>";*/

echo json_encode(array_values($messages));

function compare($a, $b) {
    error_log($a['date'] .'>'. $b['date']." is ".($a['date']>$b['date']));
    if (((int) $a['date']) == ((int) $b['date'])) {
        return 0;
    }

    return ((int) $a['date']) > ((int) $b['date']) ? -1 : 1;
}

/**
 *
 */
function getFacebookFeed($_userId, $_appId, $_secret, $_limit, $_format) {

    $res = array();
    $facebook = new Facebook(array('appId' => $_appId, 'secret' => $_secret));
    $url = 'https://api.facebook.com/method/stream.get?source_ids=' .
            $_userId . '&access_token=' . $facebook->getAccessToken() . '&limit=' . $_limit . "&format=$_format";

    $oXML = simplexml_load_file($url);
    //$code = $http_response_header[0];
    
    if ($oXML) {
        $profiles = array();
        
        foreach ($oXML->profiles->profile as $profile) {
            $profiles[(string) $profile->id] = (string) $profile->name;
        }
        
        foreach ($oXML->posts->stream_post as $stream_post) {
            $res[] = array(
                'type' => 'facebook',
                'message_id' => (string) $stream_post->post_id,
                'user_id' => (string) $stream_post->source_id,
                'name' => $profiles[(string) $stream_post->source_id],
                'text' => (string) $stream_post->message,
                'like' => (string) $stream_post->description,
                'date' => (string) $stream_post->created_time
            );
        }
    }
    
    return $res;
}

/**
 *
 *
 */
function getTwitterFeed($_user, $_count) {
    $url = 'http://twitter.com/statuses/user_timeline/' . $_user . '.xml?count=' . $_count;
    $res = array();
    $oXML = simplexml_load_file($url);
    if ($oXML) {
        foreach ($oXML->status as $oStatus) {
            $res[] = array(
                'type' => 'twitter',
                'message_id' => (string) $oStatus->id,
                'user_id' => (string) $oStatus->user->id,
                'name' => (string) $oStatus->user->name,
                'text' => (string) $oStatus->text,
                'like' => '',
                'date' => strtotime((string) $oStatus->created_at)
            );
        }
    }
    return $res;
}
